package xyz.hujf.base.ThreadWaitAndNotify;

/**
 * @author Hujf
 * @title: NotifyAll
 * @date 2021-04-2119:04
 * @description: TODO
 */
public class NotifyAll {

    private static volatile Object resA = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread thread =new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resA){
                    System.out.println("A线程锁住资源A");
                    try {
                        System.out.println("A开始等待");
                        resA.wait();
                        System.out.println("A结束等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resA){
                    System.out.println("线程B获取了资源A的锁");
                    try {
                        System.out.println("B开始等待");
                        resA.wait();
                        System.out.println("B结束等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (resA){
                System.out.println("线程C获得了资源A的锁");
                System.out.println("释放所有锁");
                resA.notifyAll();
                System.out.println("释放所有锁");
            }
        });

        thread.start();
        thread1.start();
        //确保C最后执行
        Thread.sleep(1000);
        thread2.start();

        thread.join();
        thread1.join();
        thread2.join();

        System.out.println("最后执行main线程");
    }
}
